#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python-tool 
@File    ：XIZANGWebSever.py
@IDE     ：PyCharm 
@Author  ：fanzf
@Date    ：2025/2/23 15:19 
@explain : 文件说明
"""
import base64
import datetime
import json
import time
import secrets

import redis
import requests
# from lxml import etree
# import fitz  # PyMuPDF
import os
# from pdfminer.high_level import extract_text

import traceback
from datetime import datetime
from flask import current_app
app = current_app

from .sendEmail import sendEmail

TARGET_KEYWORD = () #('EPC','采购','监理','公路','咨询','桥','设计','勘察','绿化','治理','维修','安装','农田','地勘')


try:
    # 获取项目根目录
    project_root = os.path.dirname(os.path.abspath(__file__))
    print("当前应用目录：{}".format(project_root))

    # 四川中盛城投建设工程有限公司  915100003144828070   CSP006688
    # 中科建业工程有限公司         91510000054140092D   zkjy12345
    PDF_TARGET_CONTENT = "本项目评标采用智能化评审"
    USER_NAME = {}
    fileDataLocation = os.path.join(project_root, 'json/userName.json')
    with open(fileDataLocation, 'r', encoding='utf-8') as file:
        USER_NAME = json.load(file)
    # submitFormData = {}
    # submitFormDataLocation = os.path.join(project_root, 'json/submitFormData.json')
    # with open(submitFormDataLocation, 'r', encoding='utf-8') as file:
    #     submitFormData = json.load(file)
    # 不具备报名的历史数据，持久化
    total_no_condition_enroll_data_list = []
    noConditionDataLocation = os.path.join(project_root, 'json/noConditionData.json')
    with open(noConditionDataLocation, 'r', encoding='utf-8') as file:
        total_no_condition_enroll_data_list = json.load(file)
except Exception as e:
    print(traceback.format_exc())


# 业务逻辑处理入口
def noLoginMain(cookie):
    with app.app_context():
        # 获取cookie
        cookie_str = buildCookieStr(cookie)
        # 获取登录用户信息
        user_response_dict = getUserInfo(cookie_str)
        user_name = user_response_dict["userName"]
        identity_code = user_response_dict["identify"]["organCode"]
        app.logger.info("user_name:{}".format(user_name))
        user_info = USER_NAME.get(identity_code)
        if not user_name in user_info.values():
            app.logger.error("当前登录用户不在配置中，不需要执行报名程序！！！")
            return
        # 校验分布式锁，保证同一个客户在同一时间只能执行一次
        if verifySyncLock(user_name, "locked", 7200):
            try:
                # 处理自动报名
                total_enroll_data_list = handleSignUp(cookie_str, user_response_dict, user_name)
                # 校验已关注数据是否下载标书  一天内只校验一次
                expireTime = 3600 * 24
                if verifySyncLock(user_name, "locked_submit_data", expireTime):
                    verify_result_message = verifySubmitData(cookie_str)
                else:
                    verify_result_message = "当日校验已关注数据下载标书情况，已执行，24小时内只校验一次，避免重复校验"
                # 执行完成发送消息，目前给管理员发送 1
                sendMessage(total_enroll_data_list, user_name, verify_result_message, user_info)
            finally:
                # 释放锁
                app.redis_client.delete(user_name + "locked")
        else:
            app.logger.info("{}, 正在执行报名，还未结束，请稍后再执行报名".format(user_name))


def sendMessage(total_enroll_data_list, user_name, verify_result_message, user_info):
    email_content = '<h3 style="color:red">用户在使用本工具时，请自行承担所有风险。</h3><br/>'\
                    '<h3 style="color:red">开发者不对因使用或无法使用本工具而导致的任何直接、间接、偶然、特殊或后果性损害承担责任，包括但不限于数据丢失、利润损失、业务中断或计算机故障等</h3> <br/>'
    email_content = email_content + '<b style="color:red">{} 已完成当日报名，请登录网页检查。</b> <br/>'.format(user_name)
    email_content = email_content + "<br/><b style='color:red'>当前报名项目如下：</b><br/>"
    if total_enroll_data_list:
        for index, enroll_data in enumerate(total_enroll_data_list):
            proxyResult = enroll_data.get("proxyResult")
            if proxyResult == 'success':
                email_content = email_content + enroll_data["tenderProjectName"] + " 完成报名 成功 <br/>"
            else:
                email_content = email_content + enroll_data["tenderProjectName"] + " 完成报名 <span style='color:red'>失败</span> <br/>"
    else:
        email_content = email_content + "当前没有待报名的项目<br/>"
    email_content = email_content + "<br/><b style='color:red'>校验已关注项目下载标书情况如下：</b><br/>" + verify_result_message
    # 给管理员发送消息
    sendEmail(email_content, user_name, "294010445@qq.com")
    # 给代理人发送消息
    sendEmail(email_content, user_name, "1725365556@qq.com")
    # 给公司负责人发送消息
    email = user_info["eMail"]
    if email and email != "1725365556@qq.com":
        sendEmail(email_content, user_name, email)


def handleSignUp(cookie_str, user_response_dict, user_name):
    try:
        # 切换投标人身份
        if not switchIdentity(cookie_str, user_response_dict):
            app.logger.error("{},切换投标人身份失败，当前请求不执行报名".format(user_name))
            return
        app.logger.info("开始获取未关注的数据…………")
        # 获取未关注的数据
        total_enroll_data_list = queryListDataSaved(cookie_str)
        if total_enroll_data_list:
            app.logger.info("开始循环执行报名………总共：{} 条………".format(len(total_enroll_data_list)))
            for index, enroll_data in enumerate(total_enroll_data_list):
                tenderProjectName = enroll_data["tenderProjectName"]
                app.logger.info("第{}条，可以参与报名的项目数据:{}".format(str(index + 1), tenderProjectName))
                enrollId = enroll_data["enrollId"]
                bidSectionId = enroll_data["bidSectionId"]
                tenderProjectId = getTenderProjectId(cookie_str, bidSectionId)
                # 点击关注
                enrollId = clickEnroll(cookie_str, enrollId, bidSectionId)
                # 获取当前操作“关注”的数据
                enroll_result = getEnrollResultVO(cookie_str, enrollId, bidSectionId, tenderProjectId)
                result = False
                if enroll_result:
                    # 获取项目经理信息分页查询
                    managerData = queryManagerInfo(cookie_str, enroll_result)
                    pageBean = managerData["pageBean"]
                    endNo = pageBean["endNo"]
                    resultData = managerData["result"]
                    for i in range(endNo):
                        managerData = resultData[i]["data"]
                        app.logger.info("获取项目经理信息列表第 {} 条数据：{} {}".format(i, managerData["contactName"], managerData["qualicationCode"]))
                        result = submitManagerAndData(cookie_str, enroll_result, user_name, bidSectionId, tenderProjectName, managerData)
                        if result:
                            break
                if not result:
                    enroll_data["proxyResult"] = "failed"
                else:
                    enroll_data["proxyResult"] = "success"

        else:
            app.logger.info("没有可报名数据")
    except Exception as e:
        app.logger.error("执行自动报名主方法异常：{}".format(e))
    return total_enroll_data_list


def submitManagerAndData(cookie_str, enroll_result, user_name, bidSectionId, tenderProjectName, managerData):
    enrollId = enroll_result["enrollId"]
    # 提交报名
    success = submitData(user_name, cookie_str, enroll_result, bidSectionId, tenderProjectName, managerData)
    time.sleep(5)
    if success:
        # 下载标书更新状态
        modifyDowloadFileStatus(tenderProjectName, cookie_str, enrollId)
        time.sleep(5)
        return True
    else:
        return False


def verifySyncLock(userName, lockType, expireTime):
    if app.redis_client.set(userName + lockType, lockType,  nx=True, ex=expireTime):
        return True
    else:
        return False


# 切换用户身份
def switchIdentity(cookie_str, user_response_dict):
    # 获取毫秒级时间戳（秒级时间戳乘以1000）
    timestamp_ms = int(datetime.now().timestamp() * 1000)
    identify_list = user_response_dict["identifys"]
    identity_id = ""
    for identify in identify_list:
        if "297eca616ab3d737016ab41120be0002" == identify["roleId"]:
            identity_id = identify["id"]
            break
    url = "https://ggzy.xizang.gov.cn/gfm/common/switchIdentity?identityId=" + str(identity_id) + "&timestamp=" + str(timestamp_ms)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.get(url=url, headers=headers)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        managerData = response_dict["msg"]
        if managerData == "操作成功":
            app.logger.info("切换用户身份，成功")
            return True
    else:
        app.logger.error("切换用户身份，失败：{}".format(response.content))
        return False


# 获取用户登录信息
def getUserInfo(cookie_str):
    # 获取毫秒级时间戳（秒级时间戳乘以1000）
    timestamp_ms = int(datetime.now().timestamp() * 1000)
    url = "https://ggzy.xizang.gov.cn/gfm/common/getIndexData?timestamp=" + str(timestamp_ms)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.post(url=url, headers=headers)
    if response.status_code == 200:
        response_str = response.text
        # app.logger.info("response_str:{}".format(response_str))
        response_dict = json.loads(response_str)
    return response_dict


def queryListData(cookie_str, status):
    if status == 'SUBMIT':
        option_type = '已关注'
    else:
        option_type = '未关注'
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    # 获取未关注的数据
    url = "https://ggzy.xizang.gov.cn/gb/gbEnroll/queryList?random=" + random_str
    # app.logger.debug("执行url: {}".format(url))
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    data = {
        "page": 1,
        "pageSize": 100,
        "searchName": "",
        "registerStatus": status
    }
    response = requests.post(url=url, headers=headers, json=data)
    # 已关注的数据
    total_data_list = []
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        page_bean_dict = response_dict["data"]["pageBean"]
        for result in response_dict["data"]["result"]:
            page_opers = result["pageOpers"]
            if len(page_opers) > 0:
                total_data_list.append(result["data"])
        app.logger.info("查询{}数据，分页信息：{}".format(option_type, page_bean_dict))
        pages = int(page_bean_dict["pages"])
        for page in range(2, pages + 1):
            data = {
                "page": page,
                "pageSize": 100,
                "searchName": "",
                "registerStatus": status
            }
            time.sleep(2)
            response = requests.post(url=url, headers=headers, json=data)
            if response.status_code == 200:
                # app.logger.debug("获取未关注的数据:{}".format(response.text))
                response_str = response.text
                response_dict = json.loads(response_str)
                for result in response_dict["data"]["result"]:
                    page_opers = result["pageOpers"]
                    if len(page_opers) > 0:
                        total_data_list.append(result["data"])
        app.logger.info("组装{}数据列表，总共：{} 条".format(option_type, len(total_data_list)))
    return total_data_list


# todo 没有权限查看数据  是因为请求格式必须是json格式  post请求中json=data而不是data=data
def queryListDataSaved(cookie_str):
    # 查询未关注数据
    total_data_list = queryListData(cookie_str, 'SAVED')
    # 未关注的可报名的数据
    total_enroll_data_list = []
    if not total_data_list is None:
        for index,page_data in enumerate(total_data_list):
            bid_section_id = page_data["bidSectionId"]
            bidSection_name = page_data["tenderProjectName"]
            enrollId = page_data["enrollId"]
            if not bid_section_id in total_no_condition_enroll_data_list:
                # app.logger.info("开始校验第{}条是否包含关键字：{}……".format(index+1, PDF_TARGET_CONTENT))
                # time.sleep(2)
                # viewPdfUrl = queryViewPdfUrl(cookie_str, bid_section_id, enrollId)
                # 判断是否具有报名条件 getPdfData通过pdf判断  checkeKeyWord通过关键字校验
                if checkKeyWord(bidSection_name):
                    enabel_enroll_data = {}
                    enabel_enroll_data.update({"bidSectionId":bid_section_id})
                    enabel_enroll_data.update({"tenderProjectName":bidSection_name})
                    enabel_enroll_data.update({"enrollId": enrollId})
                    total_enroll_data_list.append(enabel_enroll_data)
                    app.logger.info("可以参与报名的项目数据:{}".format(bidSection_name))
                else:
                    total_no_condition_enroll_data_list.append(bid_section_id)
            else:
                app.logger.info("第{}条已在缓存中，不需要再判断关键字：{}".format(index+1, PDF_TARGET_CONTENT))
        # 将不满足报名的数据保存在文件中
        with open(noConditionDataLocation, 'w', encoding='utf-8') as file:
            json.dump(total_no_condition_enroll_data_list, file, indent=4, ensure_ascii=False)
        return total_enroll_data_list


def checkKeyWord(tenderProjectName):
    flag = True
    for keyWord in TARGET_KEYWORD:
        if keyWord in tenderProjectName:
            app.logger.info("{} 命中关键字：{}，不报名".format(tenderProjectName, keyWord))
            flag = False
            break
    return flag


# 校验已关注的数据是否成功下载标书
def verifySubmitData(cookie_str):
    verify_result_message = ''
    # 查询已关注数据
    total_data_list = queryListData(cookie_str, 'SUBMIT')
    if not total_data_list is None:
        verify_result_message = "总共已关注数据：{}<br/>".format(len(total_data_list))
        app.logger.info(verify_result_message)
        for index,page_data in enumerate(total_data_list):
            bid_section_id = page_data["bidSectionId"]
            bidSection_name = page_data["tenderProjectName"]
            enrollId = page_data["enrollId"]
            # 根据已关注的数据查询当前用户的项目
            bidOperationList = queryCurrentUserProject(cookie_str, enrollId, bid_section_id)
            time.sleep(2)
            for item in bidOperationList:
                if item["code"] == 'TENDER_FILE':
                    operationStatus = item["operationStatus"]
                    message = "关注的第 {} 条数据 {} 标书下载情况：{} <br/>".format(index + 1, bidSection_name, operationStatus)
                    app.logger.info(message)
                    verify_result_message = verify_result_message + message + "<br/>"
                    if not '已下载' in operationStatus:
                        message = "关注的第 {} 条数据 {} <span style='color:red'>开始重新下载标书……</span>".format(index + 1, bidSection_name)
                        app.logger.info(message)
                        # 下载标书更新状态
                        modifyDowloadFileStatus(bidSection_name, cookie_str, enrollId)
                        verify_result_message = verify_result_message + message + " 完成 <br/><br/>"
                    break
                else:
                    continue
    return verify_result_message


def queryCurrentUserProject(cookie_str, enrollId, bidSectionId):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    url = "https://ggzy.xizang.gov.cn/api/register-manage/queryRegisterInfo?enrollId={}&bidSectionId={}&random={}".format(enrollId, bidSectionId, random_str)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.get(url=url, headers=headers)
    bidOperationList = []
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        bidOperationList = response_dict["data"]["bidOperationList"]
    else:
        app.logger.error(response.content)
    return bidOperationList


def queryManagerInfo(cookie_str, enroll_result):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    url = "https://ggzy.xizang.gov.cn/api/xz-person-certificate/queryCertificatesPageOld?random=" + random_str
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    enterpriseId = enroll_result["enterpriseId"]
    data = {
          "page": 1,
          "pageSize": 100,
          "searchName": "",
          "count": 0,
          "enterpriseIds": [enterpriseId],
          "extendData": {
            "personStatus": "1"
          }
    }
    response = requests.post(url=url, headers=headers, json=data)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        time.sleep(1)
        return response_dict["data"]
    else:
        app.logger.error(response.content)


def queryViewPdfUrl(cookie_str, bidSectionId, enrollId):
    url = 'https://ggzy.xizang.gov.cn/api/gbEnroll/viewpdf?bidSectionId=' + bidSectionId +'&enrollId=' + enrollId + '&random=f7a1d9cfd941b'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.get(url=url, headers=headers)
    view_pdf_url = ''
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        view_pdf_url = response_dict["data"]["domain"]["viewPdfUrl"]
    else:
        app.logger.error(response.content)
    return view_pdf_url


# def getPdfData(cookie_str, viewPdfUrl, bidSection_name):
#     url = "https://ggzy.xizang.gov.cn/api/attach/download?attachId=8a8b9819952c40640195411385913055"# + viewPdfUrl
#     headers = {
#             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
#             "Accept-Language": "zh-CN,zh;q=0.9",
#             "Accept-Encoding": "gzip, deflate, br, zstd",
#             "authorization": "token",
#             "DNT": "1",
#             "Host": "ggzy.xizang.gov.cn",
#             "Cookie": cookie_str,
#             "Cache-Control": "no-cache"
#     }
#     response = requests.get(url=url, headers=headers)
#     flag = False
#     if response.status_code == 200:
#         if checkTargetContent(response):
#             app.logger.info("{} 命中报名关键字的pdf报告url:{}".format(bidSection_name, url))
#             flag = True
#     else:
#         app.logger.error(response.content)
#     return flag


# 选择项目经理
def selectManager():
    url = "https://ggzy.xizang.gov.cn/api/xz-person-certificate/queryCertificatesPageOld?random=6a251da9af319"


# 点击关注之后，需要获取报名信息 enrollId  enterpriseId
def getEnrollResultVO(cookie_str, enrollId, bidSectionId, tenderProjectId):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    # 获取未关注的数据
    url = "https://ggzy.xizang.gov.cn/api/gbEnroll/viewEnroll?enrollId=" + enrollId + "&bidSectionId=" + bidSectionId +"&tenderProjectId=" + tenderProjectId + "&random=" + random_str
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        enroll_result = response_dict["data"]["domain"]["enrollResultVO"]
        return enroll_result
    else:
        app.logger.error(response.content)

# 获取TenderProjectId
def getTenderProjectId(cookie_str, bidSectionId):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    # 获取未关注的数据
    url = "https://ggzy.xizang.gov.cn/api/xz-project/getBidSection?bidSectionId=" + bidSectionId + "&random=" + random_str
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    response = requests.get(url=url, headers=headers)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        tender_project_id = response_dict["data"]["tenderProjectId"]
        return tender_project_id
    else:
        app.logger.error(response.content)


# 点击关注
def clickEnroll(cookie_str, enrollId, bidSectionId):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    # 获取未关注的数据
    url = "https://ggzy.xizang.gov.cn/api/gbEnroll/saveEnroll?random=" + random_str
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    data = {
      "enrollParamsVO": {
        "registerType": "0",
        "enrollId": enrollId,
        "bidSectionId": bidSectionId
      },
      "qualificationParamsVOs": [],
      "contactParamsVOs": [],
      "enterprises": []
    }
    response = requests.post(url=url, headers=headers, json=data)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        enrollId = response_dict["data"]
        return enrollId
    else:
        app.logger.error(response.content)


# 提交报名数据
def submitData(user_name, cookie_str, enroll_result, bidSectionId, tenderProjectName, managerData):
    # 创建随机数
    random_str = generate_secure_hex_random_number()
    # 获取未关注的数据
    url = "https://ggzy.xizang.gov.cn/api/xz-bidding/submitXzEnroll?random=" + random_str
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "authorization": "token",
        "DNT": "1",
        "Host": "ggzy.xizang.gov.cn",
        "Cookie": cookie_str,
        "Cache-Control": "no-cache"
    }
    data = buildSubmitData(enroll_result, managerData, bidSectionId)
    response = requests.post(url=url, headers=headers, json=data)
    if response.status_code == 200:
        response_str = response.text
        response_dict = json.loads(response_str)
        success = response_dict["success"]
        app.logger.info("{} 提交关注，响应数据：{}".format(tenderProjectName, response_dict["message"]))
        return success


def buildSubmitData(enroll_result, managerData, bidSectionId):
    enterpriseId = enroll_result["enterpriseId"]
    enrollId = enroll_result["enrollId"]
    enrollContact = enroll_result["enrollContact"]
    enrollContactPhone = enroll_result["enrollContactPhone"]
    enterpriseName = enroll_result["enterpriseName"]
    enterpriseCode = enroll_result["enterpriseCode"]
    personId = managerData["personId"]
    qualicationCode = managerData["qualicationCode"]
    contactQualication = managerData["contactQualication"]
    qualType = managerData["qualType"]
    contactName = managerData["contactName"]
    idCard = managerData["idCard"]
    data = {
        "enrollParamsVO": {
            "enterpriseCode": enterpriseCode,
            "extendsData": {
                "projectLeaderId": personId,
                "qualicationCode": qualicationCode,
                "contactQualication": contactQualication,
                "qualType": qualType
            },
            "registerType": "0",
            "enrollContactPhone": enrollContactPhone,
            "projectLeader": contactName,
            "projectLeaderIdCard": idCard,
            "enrollContact": enrollContact,
            "enterpriseName": enterpriseName,
            "projectLeaderId": personId,
            "qualicationCode": qualicationCode,
            "contactQualication": contactQualication,
            "qualType": qualType
        },
        "qualificationParamsVOs": [],
        "contactParamsVOs": [],
        "enterprises": []
    }
    enrollParamsVO = data["enrollParamsVO"]
    enrollParamsVO["syndicatedFlag"] = False
    enrollParamsVO["projectConsignerIdCard"] = None
    enrollParamsVO["registerStatus"] = None
    enrollParamsVO["enrollId"] = enrollId
    enrollParamsVO["enterpriseId"] = enterpriseId
    enrollParamsVO["projectConsigner"] = None
    enrollParamsVO["bidSectionId"] = bidSectionId
    return data


# 更新标书下载状态
def modifyDowloadFileStatus(tenderProjectName, cookie_str, enrollId):
    try:
        # 创建随机数
        random_str = generate_secure_hex_random_number()
        # 获取未关注的数据
        url = "https://ggzy.xizang.gov.cn/api/xz_upload_voucher/downBidingDoc?enrollId=" + enrollId + "&random=" + random_str
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "authorization": "token",
            "DNT": "1",
            "Host": "ggzy.xizang.gov.cn",
            "Cookie": cookie_str,
            "Cache-Control": "no-cache"
        }
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            response_str = response.text
            response_dict = json.loads(response_str)
            success = response_dict["success"]
            data = response_dict["data"]
            if success:
                app.logger.info("{} 标书下载成功：{}".format(tenderProjectName, data))
            else:
                app.logger.info("{} {}".format(tenderProjectName, data))
        else:
            app.logger.error(response.content)
    except Exception as e:
        app.logger.error("更新标书下载状态异常，{}".format(e))

def generate_secure_hex_random_number(length=13):
    # 生成足够长度的随机字节
    random_bytes = secrets.token_bytes((length + 1) // 2)
    # 将字节转换为16进制字符串
    hex_string = random_bytes.hex()
    # 如果生成的字符串长度不足13位，用前导零填充
    hex_string = hex_string[:length].zfill(length)
    return hex_string


# def checkTargetContent(response):
#     # 创建一个临时文件
#     with open(current_directory + "/temp.pdf", mode="wb") as temp_file:
#         # 将报文内容写入临时文件
#         for chunk in response.iter_content(chunk_size=1024):
#             temp_file.write(chunk)
#         # 重置文件指针到开头
#         temp_file.seek(0)
#     pdf_text = extract_text_with_pdfminer(temp_file.name)
#     # 提取图片
#     imagePath = extract_images_from_pdf(current_directory + "/temp.pdf", current_directory)
#     imageData = ocrImageData(imagePath)
#     words_result = imageData['words_result']
#     resultFlag = False
#     for word in words_result:
#         target = word['words']
#         if PDF_TARGET_CONTENT in target:
#             resultFlag = True
#             break
#     return resultFlag


# def extract_images_from_pdf(pdf_path, output_dir):
#     # 确保输出目录存在
#     if not os.path.exists(output_dir):
#         os.makedirs(output_dir)
#
#     # 打开 PDF 文件
#     doc = fitz.open(pdf_path)
#     image_count = 1
#
#     # 遍历 PDF 的每一页
#     for page_num in range(len(doc)):
#         if page_num != 1:
#             continue
#         page = doc.load_page(page_num)  # 加载当前页面
#         image_list = page.get_images(full=True)  # 获取页面中的所有图片
#
#         for img_index, img_info in enumerate(image_list):
#             xref = img_info[0]  # 获取图片的引用编号
#             base_image = doc.extract_image(xref)  # 提取图片
#             image_bytes = base_image["image"]  # 图片数据
#             image_ext = base_image["ext"]  # 图片格式（如 png,jpg）
#             # 构造保存路径
#             image_filename = os.path.join(output_dir, f"image_{page_num + 1}_{img_index + 1}.{image_ext}")
#             # 保存图片
#             with open(image_filename, "wb") as img_file:
#                 img_file.write(image_bytes)
#             print(f"Saved: {image_filename}")
#             image_count += 1
#     doc.close()  # 关闭 PDF 文件
#     return image_filename


API_KEY = "sxBbNnweqVzhlERnTRmfqMxW"
SECRET_KEY = "rMZRKooxFWKH11uRZCbt5Kfs9BkgV6ME"


def ocrImageData(path):
    # url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + get_access_token()
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + get_access_token()
    f = open(path, 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    payload = 'detect_direction=false&paragraph=false&probability=false&multidirectional_recognize=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=params)
    if response.status_code == 200:
        result = json.loads(response.text)
        print(result)
        return result


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def buildCookieStr(cookies):
    app.logger.info("cookie is {}".format(cookies))
    cookie_map = {}
    for cookie in cookies:
        cookie_map.update({cookie['name']: cookie['value']})
    cookie_str = ["{}={}".format(key, value) for key, value in cookie_map.items()]
    result = ";".join(cookie_str)
    app.logger.info("request head cookie is {}".format(result))
    return result


# def extract_text_with_pdfminer(file_path):
#     return extract_text(file_path)

